// JavaScript Document
$(document).ready(function() {
  //Function to check all checkboxes
  $("#checkAll").click(function(){
    var checked_status = this.checked;
    $("input[@name=checkBoxList]").each(function() {
      this.checked = checked_status;
    });
  });
  $('#edit-poll-search-active').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-poll-search-expire').datepicker({
    dateFormat:'mm-dd-yy'
  });

  $("#edit-poll-search-status").val('Active');

});

function applyAction(pageno, action){

  //prepare the field values for filtering
  var search_detail = $.trim($("#edit-poll-search-details").val());
  var search_active_date = $("#edit-poll-search-active").val();
  var search_expire_date = $("#edit-poll-search-expire").val();
  var search_status = $("#edit-poll-search-status").val();
  var sort = $('#hid_sort').val();
    
  //check for search criteria and return false if no value
  if (search_detail == "" && search_active_date == "" && search_expire_date == "" && search_status == "") {
    openAlertDialog(300, 125, 'Information', 'Please enter the search criteria');
    return;
  }

  $('#listingResultset').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").hide();
  $("#pagingdivbottom").hide();

  $.ajax({
    type : "POST",
    url : baseurl+"poll/actions/filter",
    data : "search_detail="+encodeURIComponent(search_detail)+"&search_active_date="+search_active_date+"&search_expire_date="+search_expire_date+"&search_status="+search_status+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
    cache : false,
    success : function (msg) {

      $("#listingResultset").html(msg);
			 
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno,10);
      var counter = $("#hid_totalRec").val();
	
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyAction('+(page+1)+',\''+action+'\')" class="red"> Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#pagingdivtop").show();
        $("#pagingdivbottom").show();
      }
		
    }
  });

}


function closeDialog(testId){
  $('#dialog').dialog('destroy');
  makeArchived(testId);
}

function createPoll(){		
  openDialog("createpoll",0,600,350,"Create Poll");
}

function edit_poll(){
  var id         = $("#edit-poll-id").val();
  var poll_title = $("#poll_title_activate").html();

  reopen_dialog(600,350,poll_title);
  editpolldialog(id);
  return false;
}

function delete_poll(){    
  var id = $("#edit-poll-id").val();

  var pageno = $("#hid_pageno").val();

  var poll_title           =  $('#poll_title_activate').html();
  if(poll_title == null){
    var poll_title           =  $('#edit-poll-title').val();
  }

  var poll_description     =  $('#poll_desc_activate').html();
  if(poll_description == null){
    var poll_description     =  $('#edit-poll-description').val();
  }

  var poll_activation_date =  $('#poll_validatefrom_activate').html();
  if(poll_activation_date == null){
    var poll_activation_date     =  $('#edit-poll-activation-date').val();
  }

  var poll_expiry_date     =  $('#poll_validateto_activate').html();
  if(poll_expiry_date == null){
    var poll_expiry_date     =  $('#edit-poll-expiry-date').val();
  }


  var poll_statuscode      =  $('#poll_status_activate').html();
  if(poll_statuscode == null){
    var poll_statuscode     =  $('#edit-poll-status').val();
  }

  var totrec = $('#hid_totalRec').val();
  var limit  = $('#hid_limit').val();


  openConfirmBox(function(){
    $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type: "POST",
      url: baseurl + 'poll/delete/'+id,
      data: '&poll_title='+ poll_title + '&poll_description=' + poll_description + '&poll_activation_date=' + poll_activation_date + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_statuscode,
      success: function(message){
        $('#dialog').dialog('destroy');
        $('#alertdialog').dialog('destroy');

								
        remainderpageno = totrec % (limit * (pageno-1));
        if(remainderpageno == 1){
          pageno--;
        }
        applyAction(pageno,$('#edit-apply').attr('actionitem'));
        if(message=="Success"){
      //openAlertDialog(300,200,"Deleted", "Poll is Sucessfully Deleted");
      }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  },300,100,"Confirm Delete","Do you want to delete the poll?");
  return false;
}



function activate_poll(){
  var pageno = $("#hid_pageno").val();
  var id                   =  $("#edit-poll-id").val();
  var poll_title           =  $('#poll_title_activate').html();
  var poll_description     =  $('#poll_desc_activate').html();
  var poll_activation_date =	$('#poll_validatefrom_activate').html();
  var poll_expiry_date     =	$('#poll_validateto_activate').html();
  var poll_statuscode      =  "Active";

  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
   
  $.ajax({
    type: "POST",
    url: baseurl + 'poll/updatepoll/'+id,
    data: '&poll_title='+ poll_title + '&poll_description=' + poll_description + '&poll_activation_date=' + poll_activation_date + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_statuscode,
    success: function(message){
      //alert(message);
      applyAction(pageno,$('#edit-apply').attr('actionitem'));
      reopen_dialog(500,220,"View poll");
      viewpolldialog(id);
      return false;			 
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

  return false;
}

function deactivate_poll(){
  var pageno               =  $("#hid_pageno").val();
  var id                   =  $("#edit-poll-id").val();
  var poll_title           =  $('#poll_title_activate').html();
  var poll_description     =  $('#poll_desc_activate').html();
  var poll_activation_date =	$('#poll_validatefrom_activate').html();
  var poll_expiry_date     =	$('#poll_validateto_activate').html();
  //var poll_statuscode      =	$('#poll_status_activate').html();
  var poll_statuscode      =  "Inactive";

  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
   
  $.ajax({
    type: "POST",
    url: baseurl + 'poll/updatepoll/'+id,
    data: '&poll_title='+ poll_title + '&poll_description=' + poll_description + '&poll_activation_date=' + poll_activation_date + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_statuscode,
    success: function(message){
      applyAction(pageno,$('#edit-apply').attr('actionitem'));
      reopen_dialog(500,220,"View poll");
      viewpolldialog(id);
      return false;			 
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

  return false;
}

function poll_action(status){
  var pageno               =  $("#hid_pageno").val();
  var poll_title              = $.trim($('#edit-poll-title').val());
  var poll_activation_date    = $.trim($("#edit-poll-activation-date").val());
  var poll_expiry_date        = $.trim($("#edit-poll-expiry-date").val());
  var poll_status             = $.trim($("#edit-poll-status").val());
  var poll_description        = $.trim($("#edit-poll-description").val());
  //var poll_description = ckeditor.getData();
	

  var str="";
  var lines = 10;
  if(poll_title==''){
    str ='Please fill the Poll title';
    lines+=18;
  }
  if(poll_title.length>50){
    if(str!="") str+= "<br/>";
    str += 'Poll title should not be more than 50 characters';
    lines+=18;
  }
  if((poll_description.length > 1000)){
    if(str!="") str+= "<br/>";
    str += 'Poll description should not be more than 1000 characters';
    lines+=18;
  }
  if(poll_activation_date==''){
    if(str!="") str+= "<br/>";
    str += 'Please fill the Poll Activation Date';
    lines+=18;
  }
 
  if(poll_status=='0'){
    if(str!="") str+= "<br/>";
    str += 'Please fill Status field';
    lines+=18;
  }

  if (poll_expiry_date != "") {
    var actObj = new Date(poll_activation_date.replace(/-/g,"/"))
    var expObj = new Date(poll_expiry_date.replace(/-/g,"/"))
    if (actObj > expObj) {
      if(str!="") str+= "<br/>";
      str += "Expiration date should be greater than or equal to the Activation date";
      lines+=18;
    }
  }


  var actdate = poll_activation_date.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(poll_expiry_date!=''){
	  var expdate = poll_expiry_date.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }


  if(str!=""){
    resize_dialog(600, 315+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return false;
  }

 /*
  if(poll_status == ''){
    var poll_statuscode = $("#edit-poll-statuscode").val();
  }
  else{
    var poll_statuscode = poll_status;
  }
  */
	
  var id = $("#edit-poll-id").val();
  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

  if(status=='add'){
    $.ajax({
      type: "POST",
      url: baseurl + 'poll/updatepoll/'+id,
      data: '&poll_title='+ encodeURIComponent(poll_title) + '&poll_description=' + encodeURIComponent(poll_description) + '&poll_activation_date=' + poll_activation_date + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_status,
      success: function(message){
        eval("var json="+message);
        if(json.Message=="Success"){
          reopen_dialog(700,470,poll_title);
          polleditQuestionDialog(id);
        }else{
          if(json.Error=="poll name already exist"){
            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $('#edit-poll-description').val(poll_description);
                $("#edit-poll-id").val(id);
				$("#edit-poll-status").val(poll_status);								
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-activation-date',0);
                styleStatusMessages("Poll name already exists", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(600,350+30);
          }
          else{
            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $('#edit-poll-description').val(poll_description);
                $("#edit-poll-id").val(id);
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-activation-date',0);
                styleStatusMessages("Failure to save poll", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });

            resize_dialog(600,350+30);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }

  if(status=='save'){
    $.ajax({
      type: "POST",
      url: baseurl + 'poll/updatepoll/'+id,
      data: '&poll_title='+ encodeURIComponent(poll_title) + '&poll_description=' + encodeURIComponent(poll_description) + '&poll_activation_date=' + poll_activation_date + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_status,
      success: function(message){
        // alert(message);
        eval("var json="+message);
        if(json.Message=="Success"){
          reopen_dialog(300,225,"Poll is Successfully Updated");
          applyAction(pageno,$('#edit-apply').attr('actionitem'));
          openAlertDialog(300, 125, 'Updated', 'Poll is Successfully Updated');
          return false;
        }else{
          if(json.Error=="poll name already exist"){
            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $('#edit-poll-description').val(poll_description);
                //ckeditor.setData(poll_description);
                $("#edit-poll-id").val(id);
				$("#edit-poll-status").val(poll_status);
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-activation-date',0);
                styleStatusMessages("Poll name already exists", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });

            resize_dialog(600,350+30);
          }
          else{
            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $('#edit-poll-description').val(poll_description);
                $("#edit-poll-id").val(id);
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-activation-date',0);
                styleStatusMessages("Failure to save poll", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });


            resize_dialog(600,350+30);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }

	




  if(status=='preview'){
    $.ajax({
      type: "POST",
      url: baseurl + 'poll/updatepoll/'+id,
      data: '&poll_title='+ poll_title + '&poll_description=' + encodeURIComponent(poll_description) + '&poll_activation_date=' + encodeURIComponent(poll_activation_date) + '&poll_expiry_date=' + poll_expiry_date + '&poll_statuscode=' + poll_status,
      success: function(message){
        eval("var json="+message);
        if(json.Message=="Success"){
          reopen_dialog(700,515,poll_title);
          previewpolldialog(id);
          return false;
        }else{
          if(json.Error=="poll name already exist"){

            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $("#edit-poll-status").val(poll_status);
                //ckeditor.setData(poll_description);
                $('#edit-poll-description').val(poll_description);
                $("#edit-poll-id").val(id);
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-expiry-date',0);
                styleStatusMessages("Poll name already exists", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(600,350+30);
          }
          else{
            $.ajax({
              type : "GET",
              url : baseurl+'poll/edit/details/'+id,
              cache : false,
              success : function (res) {
                $('#dialog').html(res);
                //fckeditor('edit-poll-description')
                $('#edit-poll-title').val(poll_title);
                $('#edit-poll-description').val(poll_description);
                $("#edit-poll-id").val(id);
                createDatePicker('edit-poll-expiry-date',0);
                createDatePicker('edit-poll-activation-date',0);
                styleStatusMessages("Failure to save poll", "statusMessage", "failure");
              },
              error : function (res) {
                handleRequestError(res);
              }
            });
            resize_dialog(600,350+30);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
  return false;
}




function preview_poll(){
  var id = $("#edit-poll-id").val();
  var poll_title =  $('#poll_title_activate').html();
  reopen_dialog(600,515,poll_title);
  previewpolldialog(id);
  return false;
}

function save_add_question(id){
  var question = $('#poll_question_ta').val();
  var questiontype = $('poll_question_type').val();
  
  var answer = $('poll_choice_text').val();
  
  $.ajax({
    type: "POST",
    url: baseurl + 'poll/updatequestions/'+id,
    data: '&question='+ question + '&questiontype=' + questiontype + '&answer=' + answer,
    success: function(message){
      $('#dialog').html(message);
      $('poll_question_type').val('');
      $('poll_question_type').val('');
      reopen_dialog(700,395,"Add Questions");
      polleditQuestionDialog(id);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function save_poll(){	
  var poll_title          = $('#edit-poll-title').val();
  var poll_activationdate = $('#edit-poll-actdate').val();
  var poll_expirydate     = $('#edit-poll-expdate').val();
  var poll_status         = $('#edit-poll-status').val();
  var pageno              = $("#hid_pageno").val();
  var poll_description    = $("#edit-poll-description").val();
  
  if(pageno == ''){
	  pageno = 1;
  }
  
  $('#statusMessage').hide();

  var lines = 10;
  var str = "";
  // var poll_description = ckeditor.getData();

  if((poll_title == '')){
    str = 'Please fill the poll title';
  }
  if((poll_title.length > 50)){
    if(str!="") str+= "<br/>";
    str += 'Poll title should not be more than 50 characters';
    lines+=18;
  }
  if((poll_description.length > 1000)){
    if(str!="") str+= "<br/>";
    str += 'Poll description should not be more than 1000 characters';
    lines+=18;
  }
  if((poll_activationdate == '')){
    if(str!="") str+= "<br/>";
    str += 'Please fill the poll activation date';
    lines+=18;
  }

  if((poll_status == '')){
    if(str!="") str+= "<br/>";
    str += 'Please fill the status field';
    lines+=18;
  }


  if (poll_expirydate != "") {
    var actObj = new Date(poll_activationdate.replace(/-/g,"/"))
    var expObj = new Date(poll_expirydate.replace(/-/g,"/"))
    if (actObj > expObj) {
      if(str!="") str+= "<br/>";
      str += "Expiration date should be greater than or equal to the Activation date";
      lines+=18;
    }
  }




  var actdate = poll_activationdate.split("-");
  if(actdate.length <3){
    if(str!="") str+= "<br/>";
    str += 'Please enter Valid date in Activation date field';
    lines+=18;
  }

  if(poll_expirydate!=''){
	  var expdate = poll_expirydate.split("-");
	  if(expdate.length <3){
		if(str!="") str+= "<br/>";
		str += 'Please enter Valid date in Expiration date field';
		lines+=18;
	  }
  }


  if(str!=""){
    resize_dialog(600, 370+lines);
    $("#createpoll_error").show();
    $("#createpoll_error").html(str);
    $('#dialog').scrollTop(0);
    return false;
  }
	
  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type: "POST",
    url: baseurl + 'poll/update',
    data: '&poll_title='+ encodeURIComponent(poll_title) + '&poll_description=' + encodeURIComponent(poll_description) + '&poll_activationdate=' + poll_activationdate+ '&poll_expirydate=' + poll_expirydate+'&poll_status=' + poll_status,
    success: function(data){

      eval("var json="+data);

      if(json.Message=="Success"){
        applyAction(pageno,$('#edit-apply').attr('actionitem'));
        openAlertDialog(300,200,"Poll Added", "New Poll is Added");
        reopen_dialog(700,395,poll_title);
        polleditQuestionDialog(json.evaluationId);
      }else{	
		
        if(json.Error!=''){
          $.ajax({
            type : "GET",
            url : baseurl+'poll/create_poll',
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-poll-expdate',0);
              createDatePicker('edit-poll-actdate',0);
              $('#edit-poll-title').val(poll_title);
              //ckeditor.setData(poll_description);
              $('#edit-poll-description').val(poll_description);
              $('#edit-poll-actdate').val(poll_activationdate);
              $('#edit-poll-expdate').val(poll_expirydate);
			  $('#edit-poll-status').val(poll_status);
			  
              $("#createpoll_error").hide();
              styleStatusMessages(json.Error, "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });

          resize_dialog(600,350+30);
        }
        else{

          $.ajax({
            type : "GET",
            url : baseurl+'poll/create_poll',
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('edit-poll-expdate',0);
              createDatePicker('edit-poll-actdate',0);
              $('#edit-poll-title').val(poll_title);
              //ckeditor.setData(poll_description);
              $('#edit-poll-description').val(poll_description);
              $('#edit-poll-actdate').val(poll_activationdate);
              $('#edit-poll-expdate').val(poll_expirydate);
              $("#createpoll_error").hide();
              styleStatusMessages("Failure to save poll", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });


          resize_dialog(600,350+30);
        }

      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function setQuestionType(type){
  $('#edit-question-type').val(type);
  $('#edit-question-insert').val(type);
  if(type == "Textbox" || type == "Textarea"){
    $('#answers_required').hide();
    $('#madatory_required').hide();
  }
  else{
    $('#answers_required').show();
    $('#madatory_required').show();
  }
}

function duplicatevalue(answers,ans){
  var flag = 0;
  for(i=0;i<answers.length;i++){
    if(answers[i][1] == ans){
      flag = 1;
    }

  }

  if(flag == 1){
    return "exist";
  }
}

var answers = new Array();
function addAnswers(){
  var ans = $.trim($('#edit-question-answer').val());

  var lines = 10;
  var strerror = "";
	
  if(ans==''){
    strerror += 'Answer Field should not be empty';
    lines+=18;
  }
  else{
    $('#add_question_error').hide();
  }
  /*
  if ( /[^A-Za-z\d \' $@%`~)(-_&]/.test(ans)) {
    strerror += 'Invalid Characters not allowed in answer field';
    lines+=18;
  }
  */

  if($.trim(strerror)!=""){
    resize_dialog(700, 495+lines);
    $('#add_question_error').show();
    $('#add_question_error').html(strerror);
    $('#dialog').scrollTop(0);
    return;
  }
    
	
  str = duplicatevalue(answers,ans);

  if(str=="exist"){
    $('#add_question_error').html('<font color=red>Same answer existing</font>');
    $('#add_question_error').show();
    ('#dialog').scrollTop(0);
    return false;
  }

  answers ='';
  answers = new Array();
	 
  tot_hidden_elements = $("#answers input:hidden").length;
  for(i=0;i<tot_hidden_elements;i++){
    answers.push([$('#edit_answerid_text'+i).val(),$('#edit_answer_text'+i).val()]);
  }
     
  answers.push([0,ans]);
  drawAnswers();
  $('#edit-question-answer').val("");
  $('#edit-question-answer').focus();
}

function removeAnswers(pos){

  openConfirmBox(function(){
    if(answers[pos][0]!=0){    
      $('#loadingtask').html('Deleting ... Please Wait....');
      $.ajax({
        type : "POST",
        url : baseurl+"poll/delete_answer/"+answers[pos][0],
        data: "status=&validateFrom=&validateTo=",
        async : false,
        cache : false,
        success : function (msg) {
          $('#alertdialog').dialog('destroy');
          if(msg=="Success"){
            $('#loadingtask').html('');
            answers.splice(pos, 1);
            drawAnswers();
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });    
    }else{
      answers.splice(pos, 1);
      $('#alertdialog').dialog('destroy');
      drawAnswers();
    }
  },300,100,"Confirm Delete","Do you want to delete the answer?");

}

function drawAnswers(){
  var str = "";
  answerid='';
  answeridvalue = '';
  for(var i=0;i<answers.length;i++){

    ansvalue = answers[i][1].replace(/\'/g,'&#39;');
		
    answerid      =  '<input type=hidden value='+answers[i][0]+'  '+'id=edit_answerid_text'+i + '>'
    answeridvalue =  '<input style=\'height:13px;font-size:10px;width:150px\' type=text value=\''+ansvalue+'\'  '+'id=edit_answer_text'+i + '>'
    str += '<div class="'+(i%2==0?"row-dark":"row-light")+'"><div class="left-title">'+answerid+'  '+answeridvalue+'</div><div class="right-text"><a href="#" onclick="removeAnswers('+i+')">Delete</a></div> <div class="clearit" style="padding:0px;"></div></div>';
  }
  $('#answers').html(str);
}

function saveQuestions(pollId, action, qid){
  var poll_title = $('#poll_title').html();
  var type               = $('#edit-question-insert').val();
  var question_mandatory = $('#edit-question-mandatory').is(':checked');
  var disp_order = $('#edit-question-displayorder').val();
  if(!disp_order || disp_order==0 || disp_order=="")
    disp_order = 1;
  var question = ckeditor.getData();

  var refusestr = question.substring(question.length-7);
  if($.trim(refusestr)=="<br />"){
    question = question.substring(0,question.length-7);
  }

    
  var lines = 10;
  var strerror = "";


  if(type=="Choose Question Type"){
    strerror += 'Select the question type';
    lines+=18;
  }
  if((question=="") || ($.trim(question)=="<br />")){
    if(strerror!="") strerror+= "<br/>";
    strerror += 'Please Fill the question';
    lines+=18;
  }

  if(type!="Textbox" && type!="Textarea"){
    if(answers.length==0){
      if(strerror!="") strerror+= "<br/>";
      strerror += 'Please Enter the answers';
      lines+=18;
    }
  }

  if(strerror!=""){
    resize_dialog(600, 495+lines);
    $('#add_question_error').show();
    $('#add_question_error').html(strerror);
    $('#dialog').scrollTop(0);
    return;
  }
  else{
    if(type == "Radio button"){
      type = "Radiobutton";
    }else if(type=="Checkbox"){
      type = "Checkbox";
    }else if(type=="Dropdown List"){
      type = "Dropdown";
    }else if(type=="Multiselect List"){
      type = "Multiselect";
    }

           		 
    var ans_str = "";
	
    for(var i=0;i<answers.length;i++){
      answers[i][1] = $('#edit_answer_text'+i).val();
      if($('#edit_answer_text'+i).val()!=""){
        ans_str+="#$#$";
	  }
	  else{
			resize_dialog(600, 495+lines);
			$('#add_question_error').show();
			$('#add_question_error').html("Answer fields should not be blank");
			$('#dialog').scrollTop(0);
			return;
	  }

      ans_str += $('#edit_answerid_text'+i).val()+","+$('#edit_answer_text'+i).val();
    }       
    //ans_str = String(ans_str).substring(1,ans_str.length);
    //alert(ans_str);
 
    if(action == 'reorder'){
      ans_str = "";
      get_answers();
      //alert(answers);
      for(var i=0;i<answers.length;i++){
        if(ans_str!="")
          ans_str+="#$#$";
        //ans_str += answers[i][0]+","+answers[i][1]+","+answers[i][2]+","+(answers[i][3]==''||answers[i][3]=='false'?'false':'true');
        ans_str += answers[i][0]+","+answers[i][1];
      }
      //alert(ans_str);
      action="edit";
    }

        
    $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"poll/updatequestions"+((action=="edit"||action=="edit_add")?"/"+qid:""),
      data: "pollid="+pollId+"&qtype="+type+"&question="+encodeURIComponent(question)+"&answers="+encodeURIComponent(ans_str)+"&question_mandatory="+question_mandatory+"&disp_order="+disp_order,
      async : false,
      cache : false,
      success : function (msg) {
        //alert(msg);
        eval("var json="+msg);
        if(json.Message=="Success"){
          answers = new Array();
          if(action=="add"||action=="edit_add"){
            if(poll_title==''){
              poll_title="Add Questions";
            }
            reopen_dialog(600,470,poll_title);
            polleditQuestionDialog(pollId);
          }else{
            if(poll_title==''){
              poll_title="Preview Questions";
            }
            reopen_dialog(600,515,poll_title);
            previewpollQuestionsDialog(pollId);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
  return false;
}



function get_answers(){
  var i=0;
  answers = new Array();
  $("#reorder li").each(function() {
    var obj = $(this).get(0).getElementsByTagName("input")[0];
    var id = obj.value;
    var ans = $(obj).next().html();
    var def = $(obj).next().next().html();
    if(def=="Default"){
      def = true;
    }else{
      def = false;
    }
    //answers[i] = ["50", ans, id, def];
    answers[i] = [ id,ans];
    i++;
  });
}




function reorderAnswers(pollId, action, qid){
  var poll_title = $('#poll_title').html();
  reopen_dialog(600,470,poll_title);
  $.ajax({
    type : "GET",
    url : baseurl+'poll/reorderanswers/'+pollId+'/'+qid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      $("#reorder ul").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {
        // $("#saveorder").show();
        }
      });

      if(($("#edit-question-insert").val()=="Textbox") || ($("#edit-question-insert").val()=="Textarea")){
        $("#madatory_required").hide();
        $("#answers_required").hide()
      }

      fckeditor('edit-question-description');
      $('#add_question_error').hide();
      $("#edit-question-insert").click(function(){
        var l = $('#edit-question-insert').position().left-1;
        var t = $('#edit-question-insert').position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });




}


function deleteSingleQuestion(sid, qid){
  openConfirmBox(function(){
    $('#dialog').html('<div style="padding-top:190px; padding-left:270px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"poll/deletequestions/"+qid,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          $('#alertdialog').dialog('destroy');
          reopen_dialog(600,475,"Preview Questions");
          previewpollQuestionsDialog(sid);
        }
      },
      error : function (res) {
        handleRequestError(res);
      }

    });
  },300,100,"Confirm Delete","Do you want to delete  this question?");
}






function editSingleQuestion(sid, qid,title){
  reopen_dialog(600,470,title);
  $.ajax({
    type : "POST",
    url : baseurl+'poll/editquestions/'+sid+'/'+qid,
    async : false,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-question-answer").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      });  

      if(($("#edit-question-insert").val()=="Textbox") || ($("#edit-question-insert").val()=="Textarea")){
        $("#madatory_required").hide();
        $("#answers_required").hide()
      }

      fckeditor('edit-question-description');
      $('#add_question_error').hide();
      $("#edit-question-insert").click(function(){
        var l = $('#edit-question-insert').position().left-1;
        var t = $('#edit-question-insert').position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        //l+=4
        //t+=33;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }

  });


}


function view_report(){
  var id  =  $("#edit-poll-id").val();
  var poll_title = $('#poll_title_activate').html();

  reopen_dialog(700,315,poll_title);

  $.ajax({
    type : "POST",
    url : baseurl+'poll/viewreport/'+id,
    async : false,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);
      $("#edit-poll-id").val(id);
    },
    error : function (res) {
      handleRequestError(res);
    }

  });

}

function polladdquestions(id){
  reopen_dialog(700,495,"Add Questions");
  polleditQuestionDialog(id);
}


var ckeditor;
function fckeditor(id){
  if(!ckeditor){
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }else{
    if (CKEDITOR.instances[id]) {
      CKEDITOR.remove(CKEDITOR.instances[id]);
    }
    ckeditor=null;
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }
  $('.ui-dialog').css("filter","");
}

function editpolldialog(id){

  $.ajax({
    type : "POST",
    url : baseurl+'poll/edit/details/'+id,
    async : false,
    cache : false,
    success : function (msg) {
      $('#dialog').html(msg);
      $("#edit-poll-id").val(id);
      createDatePicker('edit-poll-expiry-date',0);
      createDatePicker('edit-poll-activation-date',0);

    },
    error : function (res) {
      handleRequestError(res);
    }

  });

}

function viewpolldialog(id){
  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

  $.ajax({
    type : "GET",
    url : baseurl+'poll/details/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-poll-id").val(id);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function polleditQuestionDialog(id){	

  $.ajax({
    type : "GET",
    url : baseurl+'poll/editquestions/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-question-answer").keyup(function(e) {
        if(e.keyCode == 13) {
          addAnswers();
        }
      }); 

      fckeditor('edit-question-description');
      $('#add_question_error').hide();
      $("#edit-question-insert").click(function(){
        var l = $('#edit-question-insert').position().left-1;
        var t = $('#edit-question-insert').position().top+22;
        if($.browser.msie && $.browser.version<8){
          l-=5;
        }
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function previewpolldialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'poll/preview/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function previewpollQuestionsDialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'poll/preview/'+id+"/1/30",
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function backtoDetails(id){
  reopen_dialog(500,210,"View poll");
  viewpolldialog(id);
}
function filterdata_poll(){
  //prepare the field values for filtering
  var search_detail = $.trim($("#edit-poll-search-details").val());
  var search_active_date = $("#edit-poll-search-active").val();
  var search_expire_date = $("#edit-poll-search-expire").val();
  var search_status = $("#edit-poll-search-status").val();
    
  var data = "";
  if($.trim(search_detail)!=""){
    data+="&search_detail="+search_detail;
  }
  if($.trim(search_active_date)!=""){
    data+="&search_active_date="+search_active_date;
  }
  if($.trim(search_status)!="" && search_status != "ANY"){
    data+="&search_status="+search_status;
  }
  if($.trim(search_expire_date)!=""){
    data+="&search_expire_date="+search_expire_date;
  }
  return data;
}



function questionreorder(pollid){
  $('#dialog').html('<div style="padding-top:190px; padding-left:270px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'poll/reorderquestions/'+pollid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      $("#reorder ul").sortable({
        opacity: 0.8,
        cursor: 'move',
        update: function() {
          $("#saveorder").show();
        }
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}





//Function to save the reordered list
function save_reorder (id) {
  var neworder = Array();
  $("#reorder .gridlister").each(function() {
    neworder.push($(this).attr("id").split("_")[1]);
  });

  $('#dialog').html('<div style="padding-top:240px; padding-left:305px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    data : "newOrder="+neworder,
    url : baseurl+'poll/reorder/save/'+id,
    async : false,
    cache : false,
    success : function (msg) {
      eval("var json="+msg);
      if(json.Message=="Success"){
        previewpollQuestionsDialog(id);
			
      }
    },
    error : function (res) {
      handleRequestError(res);
    }

  });
}


